<?php

namespace addons\qingdong\controller;

use addons\qingdong\model\Achievement as AchievementModel;
use addons\qingdong\model\AchievementRecords;
use addons\qingdong\model\ExamineRecord;
use addons\qingdong\model\Flow;
use addons\qingdong\model\Message;
use addons\qingdong\model\StaffDepartment;
use addons\qingdong\model\Staff;
use think\Db;
use think\Exception;

/**
 * 业绩管理接口
 */
class Achievement extends StaffApi {
	protected $noNeedLogin = [];
	protected $noNeedRight = [];


    /**
     * 部门列表
     */
	public function getDepartment() {
		$department = StaffDepartment::where([])->field('id,name')->select();
		$department = array_merge([['id' => 0, 'name' => '全部']], $department);

		$this->success('请求成功', ['department' => $department, 'years' => getYears()]);
	}


    /**
     * 获取员工业绩目标
     */
	public function getStaffList() {
		$department_id = input('department_id');
		$year          = input('year', date('Y'), 'intval');
		$status        = input('status', 1);
		$where         = [];
		if ($department_id) {
			$where['department_id'] = $department_id;
		}
		$where['status'] = 1;
		$staffModel      = new Staff();
		$staffs          = $staffModel->where($where)->field('id,name,img,post')->with([
			'achievement' => function ($query) use ($year, $status) {
				$query->where(['year' => $year, 'status' => $status])->field('yeartarget,obj_id');
			},
			'department'
		])->select();

		foreach ($staffs as $k => $v) {
			if (empty($v['achievement'])) {
				$v['achievement'] = ['yeartarget' => 0];
			}
			$staffs[$k] = $v;
		}

		$this->success('请求成功', $staffs);
	}


    /**
     * 获取部门业绩列表
     */
	public function getDepartmentList() {
		$year   = input('year', date('Y'), 'intval');
		$status = input('status', 1);

		$departmentModel = new StaffDepartment();
		$staffs          = $departmentModel->where([])->field('id,name')->with([
			'achievement' => function ($query) use ($year, $status) {
				$query->where(['year' => $year, 'status' => $status])->field('yeartarget,obj_id');
			},
		])->select();

		foreach ($staffs as $k => $v) {
			if (empty($v['achievement'])) {
				$v['achievement'] = ['yeartarget' => 0];
			}
			$staffs[$k] = $v;
		}

		$this->success('请求成功', $staffs);
	}


    /**
     * 获取团队业绩
     */
	public function getTeamList() {
		$year   = input('year', date('Y'), 'intval');
		$status = input('status', 1);

		$staffModel = new Staff();
		//1最高管理员 2公司管理员 3部门经理 4部门主管 5组长 6员工
		$staffs = $staffModel->where([
			'role'     => ['in', [1, 2, 3, 4, 5]]
		])->field('id,name,img,post')->with([
			'teamAchievement' => function ($query) use ($year, $status) {
				//团队
				$query->where(['year' => $year, 'status' => $status])->field('yeartarget,obj_id');
			},
		])->select();
		$staffs = collection($staffs)->toArray();
		foreach ($staffs as $k => $v) {
			$v['achievement'] = $v['team_achievement'] ?? ['yeartarget' => 0];
			unset($v['team_achievement']);
			$staffs[$k] = $v;
		}

		$this->success('请求成功', $staffs);
	}


    /**
     * 获取公司目标
     */
	public function getCompanyAchievement() {
		$year         = input('year', date('Y'), 'intval');
		$status       = input('status', 1);//1销售（目标）2回款（目标）
		$model        = new AchievementModel();
		$achievements = $model->where([
			'type'     => 1,
			'obj_id'   => 1,
			'year'     => $year,
			'status'   => $status
		])->find();
		if (empty($achievements)) {
			$model->save(['type' => 1, 'year' => $year, 'status' => $status]);
			$achievements = $model->where(['type' => 1, 'year' => $year, 'status' => $status])->find();
		}

		$this->success('请求成功', $achievements);
	}


    /**
     * 获取目标
     */
	public function getMyAchievementDetail() {
		$year   = input('year', date('Y'), 'intval');
		$status = input('status', 1);//1销售（目标）2回款（目标）

		$model = new AchievementModel();
		$row   = $model->where([
			'obj_id'   => $this->auth->id,
			'type'     => 3,
			'year'     => $year,
			'status'   => $status
		])->find();
		$this->success('请求成功', $row);
	}

    /**
     * 获取目标详情
     */
	public function getAchievementDetail() {
		$type   = input('type');
		$year   = input('year', date('Y'), 'intval');
		$status = input('status', 1);//1销售（目标）2回款（目标）
		$ids    = input('ids');
		if (empty($ids)) {
			$this->error('参数不能为空');
		}
		$ids   = explode(',', $ids);
		$model = new AchievementModel();
		$row   = $model->where([
			'obj_id'   => $ids[0],
			'type'     => $type,
			'year'     => $year,
			'status'   => $status
		])->find();
		$this->success('请求成功', $row);
	}


    /**
     * 添加或修改目标
     */
	public function addAchievement() {
		$type         = input('type');
		$year         = input('year', date('Y'), 'intval');
		$status       = input('status', 1);//1销售（目标）2回款（目标）
		$achievements = input('achievements/a');
		$ids          = input('ids');
		$yeartarget          = input('yeartarget',0);
		$model        = new AchievementModel();
		$ids          = explode(',', $ids);
		$insertAll    = [];
		foreach ($ids as $id) {
			$insertAll[] = [
				'type'       => $type,
				'year'       => $year,
				'status'     => $status,
				'obj_id'     => $id,
				'january'    => $achievements['january'] ?? 0,
				'february'   => $achievements['february'] ?? 0,
				'march'      => $achievements['march'] ?? 0,
				'april'      => $achievements['april'] ?? 0,
				'june'       => $achievements['june'] ?? 0,
				'may'        => $achievements['may'] ?? 0,
				'july'       => $achievements['july'] ?? 0,
				'august'     => $achievements['august'] ?? 0,
				'september'  => $achievements['september'] ?? 0,
				'october'    => $achievements['october'] ?? 0,
				'november'   => $achievements['november'] ?? 0,
				'december'   => $achievements['december'] ?? 0,
				'yeartarget' => $yeartarget,
				'createtime' => time(),
				'updatetime' => time()
			];
		}
		Db::startTrans();
		try {
			$model->where([
				'obj_id'   => ['in', $ids],
				'type'     => $type,
				'year'     => $year,
				'status'   => $status
			])->delete();

			if ($model->insertAll($insertAll) == false) {
				throw new Exception('提交失败');
			}
			Db::commit();;
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}

		$this->success('提交成功！');
	}


    /**
     * 获取目标详情
     */
	public function staffEditAchievement() {
		$type         = 3;//员工
		$year         = input('year', date('Y'), 'intval');
		$status       = input('status', 1);//1销售（目标）2回款（目标）
		$achievements = input('achievements/a');
		$flow_staff_id = input('flow_staff_ids');
        $yeartarget          = input('yeartarget',0);

		$model        = new AchievementRecords();
		$id = $this->auth->id;
		$params = [
			'type'          => $type,
			'year'          => $year,
			'status'        => $status,
			'obj_id'        => $id,
			'january'       => $achievements['january'] ?? 0,
			'february'      => $achievements['february'] ?? 0,
			'march'         => $achievements['march'] ?? 0,
			'april'         => $achievements['april'] ?? 0,
			'june'          => $achievements['june'] ?? 0,
			'may'           => $achievements['may'] ?? 0,
			'july'          => $achievements['july'] ?? 0,
			'august'        => $achievements['august'] ?? 0,
			'september'     => $achievements['september'] ?? 0,
			'october'       => $achievements['october'] ?? 0,
			'november'      => $achievements['november'] ?? 0,
			'december'      => $achievements['december'] ?? 0,
			'flow_staff_ids' => $flow_staff_id,
            'owner_staff_id'=> $this->auth->id,
			'check_status'  => 0,
			'yeartarget'    => $yeartarget,
			'createtime'    => time(),
			'updatetime'    => time()
		];

		Db::startTrans();
		try {

            $flow = Flow::getsteplist(Flow::ACHIEVEMENT_STATUS);
            $params['flow_id'] = $flow['flow_id'];
            $params['order_id'] = $flow['order_id'];

            if ($flow['status'] == 0) {//发起人自选
                if (empty($params['flow_staff_ids'])) {
                    throw new Exception('审批人必须选择');
                }
                $params['flow_staff_ids'] = trim($params['flow_staff_ids']);
            } else {
                if (empty($flow['flow_staff_ids'])) {
                    throw new Exception('没有直属上级无法审批，请联系管理员！');
                }
                $params['flow_staff_ids'] = trim($flow['flow_staff_ids']);
            }

			if ($model->insert($params) === false) {
				throw new Exception('添加失败');
			}
			$lastId     = $model->getLastInsID();

            if ($flow['status'] == 1) {//固定审批
                //发送审批通知
                Flow::sendStepRecord($flow,Flow::ACHIEVEMENT_STATUS, $lastId);
            } else {//发起人自选 依次审批
                $staff_id   = explode(',', $params['flow_staff_ids'])[0];
                if ($staff_id) {
                    ExamineRecord::addExaminse(ExamineRecord::ACHIEVEMENT_TYPE, $lastId, $staff_id);
                }
            }
			Db::commit();;
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}

		$this->success('提交成功，等待审核！');
	}

    /**
     * 员工自己修改目标
     */
	public function editRecords(){
		$department_id = input('department_id');
		$year          = input('year', date('Y'), 'intval');
		$status        = input('status', 1);
		$limit         = input("limit/d", 10);
		$where         = [];
		if ($department_id) {
			$where['department_id'] = $department_id;
		}
		$where['year'] = $year;
		$where['status'] = $status;

		$model        = new AchievementRecords();

		$list = $model->where(['type'=>3,'obj_id'=>$this->auth->id])->where($where)->with(['staff'])->order('id desc')->paginate($limit);
		
		$this->success('请求成功',$list);
	}

    /**
     * 获取业绩详情表
     */
	public function getRecordsDetail(){
		$id=input('id');
		$model        = new AchievementRecords();

		$records = $model->where(['id'=>$id])->with(['staff'])->find();
		if (empty($records)) {
			$this->error('业绩目标不存在');
		}

		if ($records['check_status'] == 0 || $records['check_status'] == 1) {
			$records['is_examine'] = ExamineRecord::isExaminse(ExamineRecord::ACHIEVEMENT_TYPE, $id);
		} else {
			$records['is_examine'] = 0;
		}
		//标记通知已读
		Message::setRead(Message::ACHIEVEMENT_TYPE, $id, $this->auth->id);
		$this->success('请求成功', $records);
	}
}
